<template>
  <div class="admin-settings">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>账号设置</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 修改密码 -->
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码"
              />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form
            ref="securityFormRef"
            :model="securityForm"
            label-width="180px"
          >
            <el-form-item label="登录验证">
              <el-switch
                v-model="securityForm.loginVerification"
                active-text="开启"
                inactive-text="关闭"
              />
              <div class="form-tip">开启后登录时需要输入验证码</div>
            </el-form-item>
            <el-form-item label="异地登录提醒">
              <el-switch
                v-model="securityForm.locationAlert"
                active-text="开启"
                inactive-text="关闭"
              />
              <div class="form-tip">开启后检测到异地登录时会发送提醒</div>
            </el-form-item>
            <el-form-item label="登录设备管理">
              <el-button type="primary" @click="handleManageDevices">
                管理登录设备
              </el-button>
              <div class="form-tip">查看并管理已登录的设备</div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveSecurity">
                保存设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <el-form
            ref="notificationFormRef"
            :model="notificationForm"
            label-width="180px"
          >
            <el-form-item label="系统通知">
              <el-switch
                v-model="notificationForm.systemNotification"
                active-text="开启"
                inactive-text="关闭"
              />
              <div class="form-tip">接收系统更新、维护等通知</div>
            </el-form-item>
            <el-form-item label="安全通知">
              <el-switch
                v-model="notificationForm.securityNotification"
                active-text="开启"
                inactive-text="关闭"
              />
              <div class="form-tip">接收账号安全相关的通知</div>
            </el-form-item>
            <el-form-item label="通知方式">
              <el-checkbox-group v-model="notificationForm.notificationMethods">
                <el-checkbox label="email">邮件</el-checkbox>
                <el-checkbox label="sms">短信</el-checkbox>
                <el-checkbox label="system">站内信</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveNotification">
                保存设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 登录设备管理对话框 -->
    <el-dialog
      v-model="devicesDialogVisible"
      title="登录设备管理"
      width="600px"
      :append-to-body="true"
    >
      <el-table :data="loginDevices" style="width: 100%">
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="location" label="登录地点" />
        <el-table-column prop="time" label="最后登录时间" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="danger"
              link
              @click="handleLogoutDevice(row)"
            >
              退出登录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 当前激活的标签页
const activeTab = ref('password')

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 安全设置表单
const securityFormRef = ref(null)
const securityForm = ref({
  loginVerification: true,
  locationAlert: true
})

// 通知设置表单
const notificationFormRef = ref(null)
const notificationForm = ref({
  systemNotification: true,
  securityNotification: true,
  notificationMethods: ['email', 'system']
})

// 登录设备管理
const devicesDialogVisible = ref(false)
const loginDevices = ref([
  {
    device: 'Chrome / Windows 10',
    location: '北京',
    time: '2024-03-15 10:30:00'
  },
  {
    device: 'Safari / iOS 15',
    location: '上海',
    time: '2024-03-14 15:20:00'
  }
])

// 处理修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟API调用
      ElMessage.success('密码修改成功')
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  })
}

// 处理保存安全设置
const handleSaveSecurity = () => {
  // 模拟API调用
  localStorage.setItem('adminSecuritySettings', JSON.stringify(securityForm.value)); // 保存到 localStorage
  ElMessage.success('安全设置保存成功')
}

// 处理保存通知设置
const handleSaveNotification = () => {
  // 模拟API调用
  localStorage.setItem('adminNotificationSettings', JSON.stringify(notificationForm.value)); // 保存到 localStorage
  ElMessage.success('通知设置保存成功')
}

// 处理管理登录设备
const handleManageDevices = () => {
  devicesDialogVisible.value = true
}

// 处理退出设备登录
const handleLogoutDevice = (row) => {
  // 模拟API调用
  ElMessage.success(`已退出设备 ${row.device} 的登录`)
  loginDevices.value = loginDevices.value.filter(device => device.device !== row.device)
}

// 加载设置
const loadSettings = () => {
  const savedSecuritySettings = localStorage.getItem('adminSecuritySettings');
  if (savedSecuritySettings) {
    try {
      Object.assign(securityForm.value, JSON.parse(savedSecuritySettings));
    } catch (e) {
      console.error('Failed to load admin security settings from localStorage:', e);
    }
  }

  const savedNotificationSettings = localStorage.getItem('adminNotificationSettings');
  if (savedNotificationSettings) {
    try {
       // Ensure notificationMethods is an array if it's null or undefined in localStorage
       const loadedNotificationSettings = JSON.parse(savedNotificationSettings);
       if (!Array.isArray(loadedNotificationSettings.notificationMethods)) {
         loadedNotificationSettings.notificationMethods = [];
       }
      Object.assign(notificationForm.value, loadedNotificationSettings);
    } catch (e) {
      console.error('Failed to load admin notification settings from localStorage:', e);
    }
  }
};

onMounted(() => {
  loadSettings(); // 在组件挂载时加载设置
})
</script>

<style scoped>
.admin-settings {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style> 